import * as Cesium from '@cesiumjs';

var _ellipsoidGeodesic = undefined;

function $getEllipsoidGeodesic() {
  if (!_ellipsoidGeodesic) {
    _ellipsoidGeodesic = new Cesium.EllipsoidGeodesic();
  }
  return _ellipsoidGeodesic;
}

function calcHeight(ratio, distance) {
  let dis = distance / 30000000;
  dis = Math.min(1, dis);
  dis = 1 - Math.pow(1 - dis, 2);
  return Math.sin(Math.PI * ratio) * 1000000 * dis;
}

//xbsjCreateTransmitPolyline
// function xbsjCreateTransmitPolyline(startPos, endPos, minDistance) {
// var heightRatio = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;
function g3d_createTransmitPolyline(startPos, endPos, heightRatio, minDistance) {
  heightRatio = heightRatio || 1;
  var ellipsoidGeodesic = $getEllipsoidGeodesic();
  var positions = Cesium.Cartesian3.fromRadiansArray([startPos[0], startPos[1], endPos[0], endPos[1]]);
  var height = [0, 0];
  if (startPos.length >= 3 && endPos.length >= 3) {
    height = [startPos[2], endPos[2]];
  }
  const points = Cesium.PolylinePipeline.generateCartesianArc({
    positions,
    height,
    minDistance
  });
  var start = Cesium.Cartographic.fromRadians(startPos[0], startPos[1]);
  var end = Cesium.Cartographic.fromRadians(endPos[0], endPos[1]);
  ellipsoidGeodesic.setEndPoints(start, end);
  var distance = ellipsoidGeodesic.surfaceDistance;
  const WGS84 = Cesium.Ellipsoid.WGS84;
  var numPt = points.length;
  points.forEach((point, i) => {
    var h = calcHeight(i / (numPt - 1), distance * heightRatio);
    var cartographic = Cesium.Cartographic.fromCartesian(point);
    cartographic.height += h;
    const {
      longitude,
      latitude,
      height
    } = cartographic;
    Cesium.Cartesian3.fromRadians(longitude, latitude, height, WGS84, point);
  });
  return points;
}

export default g3d_createTransmitPolyline;
